/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package rentcalculator.persist;

import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;

/**
 *
 * @author developer
 */
class Persist {

    static Persist persist = null;
    
    private Persist(){
       
    }
    
    static Persist getInstance(){
        if(persist == null ){
            persist = new Persist();
        }
        
        return persist;
    }
    
     
    void update(Object m) {
       Session s = SessionController.getInstance().getSession();
        
        s.update(m);
        s.flush();
        s.close();
    }

 
    void add(Object m) {
         Session s = SessionController.getInstance().getSession();
        
        s.save(m);
        s.flush();
        s.close();
       
    }

 
    void remove(Object m) {
        Session s = SessionController.getInstance().getSession();
        
        s.delete(m);
        s.flush();
        s.close();
    }
    
 
    List findALL(Class c) {
        Session s = SessionController.getInstance().getSession();
        
        List lps = s.createCriteria(c).list();
        
        s.close();
        return lps;
    }

 
    Object findById(Class c, long id) {
        Session s = SessionController.getInstance().getSession();
        Object o = s.get(c, id);
        
        
        s.close();
        
        return o;
    }
    
    
    List find(Class c, List<Criterion> cs, List<Order> os){
        Session s = SessionController.getInstance().getSession();
        Criteria criteria = s.createCriteria(c);
        for (Criterion criterion : cs ){
            criteria.add(criterion);
            
        }
        
        for (Order order : os ){
            criteria.addOrder(order);
            
        }
        
        List result = criteria.list();
        
        
        s.close();
        
        return result;
        
    }
    
    
    List find(Class c, String sql, Map<String, String> cs){
        Session s = SessionController.getInstance().getSession();
        SQLQuery sqlQuery = s.createSQLQuery(sql).addEntity(c);
        for(String key :cs.keySet()){
            sqlQuery.setString(key, cs.get(key));
        }
        List result = sqlQuery.list();
        
        s.close();
        
        
        return result;
        
    }
}
